package com.yinhai.dao;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.CallLog;
import android.provider.ContactsContract;

import com.yinhai.activity.R;
import com.yinhai.model.PhoneRecord;
import com.yinhai.service.ContactUserServiceImpl;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 历史通话记录
 *
 * @author Administrator
 */
public class PhoneRecordDaoImpl {

    private List<PhoneRecord> phoneRecords;

    private Map<String, PhoneRecord> recordMap;

    private boolean flag = false;

    ContentResolver contentResolver;

    public PhoneRecordDaoImpl(Context context) {
        contentResolver = context.getContentResolver();
    }

    /**
     * 获取所有历史通话记录 0为全部 来电：CallLog.Calls.INCOMING_TYPE （常量值：1） 已拨：CallLog.Calls.OUTGOING_TYPE（常量值：2）
     * 未接：CallLog.Calls.MISSED_TYPE（常量值：3） 其实还有一种类型-拒接 系统未给出常量。但经测试后得出结论为4.
     *
     * @return
     */
    public List<PhoneRecord> find(int phoneType, String telnumber) {
        Uri uri = android.provider.CallLog.Calls.CONTENT_URI;
        // 查询的列
        String[] projection = {CallLog.Calls.DATE, // 日期
                CallLog.Calls.NUMBER, // 号码
                CallLog.Calls.TYPE, // 类型
                CallLog.Calls.CACHED_NAME, // 名字
                CallLog.Calls._ID, // id
                CallLog.Calls.DURATION // 通话时长

        };
        Cursor cursor = null;
        if (phoneType == 0) {
            if (telnumber.equals("")) {
                cursor = contentResolver.query(uri, projection, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
            } else {
                cursor =
                        contentResolver.query(uri,
                                projection,
                                "number=" + telnumber,
                                null,
                                CallLog.Calls.DEFAULT_SORT_ORDER);
            }

        } else {
            cursor =
                    contentResolver.query(uri, projection, "type=" + phoneType, null, CallLog.Calls.DEFAULT_SORT_ORDER);
        }

        phoneRecords = new ArrayList<PhoneRecord>();
        if (cursor != null && cursor.getCount() > 0) {
            recordMap = new HashMap<String, PhoneRecord>();
            PhoneRecord p = null;
            SimpleDateFormat sfd = new SimpleDateFormat("HH:mm");
            SimpleDateFormat yearMonthDay = new SimpleDateFormat("yyyy-MM-dd");
            Date date;
            cursor.moveToFirst(); // 游标移动到第一项
            for (int i = 0; i < cursor.getCount(); i++) {
                cursor.moveToPosition(i);
                date = new Date(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));
                String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
                String cachedName = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));// 缓存的名称与电话号码，如果它的存在
                if (ContactUserServiceImpl.phoneNames.get(number.indexOf("+86") == 0 ? number.substring(3,
                        number.length()) : number) == null) {
                    cachedName = number;// 电话号码
                } else {
                    cachedName =
                            ContactUserServiceImpl.phoneNames.get(number.indexOf("+86") == 0 ? number.substring(3,
                                    number.length()) : number);
                }

                int id = cursor.getInt(cursor.getColumnIndex(CallLog.Calls._ID));

                String duration = Long.toString(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION)));

                PhoneRecord phoneRecord = new PhoneRecord();
                phoneRecord.setId(id);
                phoneRecord.setTelPhone(number);
                if (cachedName == null || cachedName.equals("")) {
                    phoneRecord.setName("未知联系人");
                } else {
                    phoneRecord.setName(cachedName);
                }

                phoneRecord.setType(type + "");
                phoneRecord.setYearMonth(yearMonthDay.format(date));
                phoneRecord.setTime(sfd.format(date));
                phoneRecord.setArea("");
                phoneRecord.setPhoneType("");
                phoneRecord.setDuration(duration);
//                phoneRecord.headerUlr = getContactPhoto(id);
                
                /*
                 * p = recordMap.get(number); if(p == null) { recordMap.put(number, phoneRecord); } else {
                 * p.setCount((p.getCount()+1)); recordMap.put(number, p); }
                 */
                phoneRecords.add(phoneRecord);

            }
            cursor.close();
        }

        if (cursor != null) {
            cursor.close();
        }
        
        /*
         * Iterator<String> iterator = recordMap.keySet().iterator(); String key = null; while(iterator.hasNext()) { key
         * = iterator.next(); phoneRecords.add(recordMap.get(key)); }
         */
        return phoneRecords;
    }

    private static Uri getContactPhoto(int personId) {
        Uri uri = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, personId);
        return uri;

    }

}
